import sys
import json
import os


def main():
    try:
        # Check command-line arguments
        if len(sys.argv) != 3:
            raise ValueError("Usage: python script.py <json1> <json2>")

        # Get file paths and validate extensions
        file1, file2 = sys.argv[1], sys.argv[2]
        for f in [file1, file2]:
            if not os.path.exists(f):
                raise FileNotFoundError(f"File not found: {f}")
            if not f.lower().endswith(".json"):
                raise ValueError("Only JSON files are supported")

        # Read JSON files
        with open(file1, "r") as f1, open(file2, "r") as f2:
            data1 = json.load(f1)
            data2 = json.load(f2)

        # Verify list structure
        if not (isinstance(data1, list) and isinstance(data2, list)):
            raise TypeError("Both JSON files must contain lists")

        # Create combined structure
        combined = {
            os.path.splitext(os.path.basename(file1))[0]: data1,
            os.path.splitext(os.path.basename(file2))[0]: data2,
        }

        # Create output directory
        output_dir = os.path.splitext(os.path.basename(file1))[0]
        os.makedirs(output_dir, exist_ok=True)

        # Save combined JSON
        output_path = os.path.join(output_dir, "combined.json")
        with open(output_path, "w") as outfile:
            json.dump(combined, outfile, indent=2, ensure_ascii=False)

        print(f"Combined JSON saved to: {output_path}")

    except Exception as e:
        print(f"Error: {str(e)}")
        sys.exit(1)


if __name__ == "__main__":
    main()
